package com.greateamd.timetableasy.client.widgets.university;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.greateamd.timetableasy.client.services.university.UniversityService;
import com.greateamd.timetableasy.client.services.university.UniversityServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.client.widgets.ListBox;
import com.greateamd.timetableasy.domain.University;

public class UniversityListBox extends ListBox 
{
	private List<University> universities;
	
	public @UiConstructor UniversityListBox(boolean autoLoad) {
		super(false);
		if(autoLoad){
			loadUniversities();
		}
	}	

	public void loadUniversities() {
		final UniversityServiceAsync userService = GWT.create(UniversityService.class);
		new ServerCall<List<University>>() {

			@Override
			protected void callService(AsyncCallback<List<University>> asyncCallback) {
				userService.getAll(asyncCallback);
			}

			@Override
			public void onSuccess(List<University> entities) {
				universities = entities;
				showList();
			}
		}.call();
	}

	protected void showList() {
		clear();
		for(University u : universities){
			addItem(u.getName());
		}
	}
	
	public University getSelectedUniversity(){
		return universities.get(getSelectedIndex());
	}
}
